{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "01cd5f13",
   "metadata": {},
   "outputs": [],
   "source": [
    "#!pip install langchain_experimental"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "cb702343",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_experimental.agents.agent_toolkits import create_python_agent\n",
    "from langchain_experimental.tools import PythonREPLTool\n",
    "from langchain_openai import ChatOpenAI"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "8e6d70d3-4c5a-4574-bc90-a3b29f88eff7",
   "metadata": {},
   "outputs": [],
   "source": [
    "tools = [PythonREPLTool()]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "cb5be2dd",
   "metadata": {},
   "outputs": [],
   "source": [
    "agent_executor = create_python_agent(\n",
    "    llm=ChatOpenAI(model=\"gpt-3.5-turbo\", temperature=0),\n",
    "    tool=PythonREPLTool(),\n",
    "    verbose=True,\n",
    "    agent_executor_kwargs={\"handle_parsing_errors\": True}\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "513ce1e5",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "AgentExecutor(verbose=True, agent=ZeroShotAgent(llm_chain=LLMChain(prompt=PromptTemplate(input_variables=['agent_scratchpad', 'input'], template='You are an agent designed to write and execute python code to answer questions.\\nYou have access to a python REPL, which you can use to execute python code.\\nIf you get an error, debug your code and try again.\\nOnly use the output of your code to answer the question. \\nYou might know the answer without running any code, but you should still run the code to get the answer.\\nIf it does not seem like you can write code to answer the question, just return \"I don\\'t know\" as the answer.\\n\\n\\nPython_REPL: A Python shell. Use this to execute python commands. Input should be a valid python command. If you want to see the output of a value, you should print it out with `print(...)`.\\n\\nUse the following format:\\n\\nQuestion: the input question you must answer\\nThought: you should always think about what to do\\nAction: the action to take, should be one of [Python_REPL]\\nAction Input: the input to the action\\nObservation: the result of the action\\n... (this Thought/Action/Action Input/Observation can repeat N times)\\nThought: I now know the final answer\\nFinal Answer: the final answer to the original input question\\n\\nBegin!\\n\\nQuestion: {input}\\nThought:{agent_scratchpad}'), llm=ChatOpenAI(client=<openai.resources.chat.completions.Completions object at 0x122912c90>, async_client=<openai.resources.chat.completions.AsyncCompletions object at 0x12291e150>, temperature=0.0, openai_api_key=SecretStr('**********'), openai_proxy='')), output_parser=MRKLOutputParser(), allowed_tools=['Python_REPL']), tools=[PythonREPLTool()], handle_parsing_errors=True)"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "agent_executor"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "3c41ffe5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Python REPL can execute arbitrary code. Use with caution.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[32;1m\u001b[1;3mWe can use Python to calculate 7 to the power of 2.3.\n",
      "Action: Python_REPL\n",
      "Action Input: print(7 ** 2.3)\u001b[0m\n",
      "Observation: \u001b[36;1m\u001b[1;3m87.84670816352883\n",
      "\u001b[0m\n",
      "Thought:\u001b[32;1m\u001b[1;3mThe result of 7 to the power of 2.3 is approximately 87.85.\n",
      "Final Answer: 87.85\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'input': '7的2.3次方是多少？', 'output': '87.85'}"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "agent_executor.invoke({\"input\": \"7的2.3次方是多少？\"})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "5d3da1ea",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3m我们可以使用循环或递归来计算斐波那契数列的第12个数字。\n",
      "Action: Python_REPL\n",
      "Action Input: def fibonacci(n):\n",
      "                if n <= 1:\n",
      "                    return n\n",
      "                else:\n",
      "                    return fibonacci(n-1) + fibonacci(n-2)\n",
      "            print(fibonacci(12))\u001b[0m\n",
      "Observation: \u001b[36;1m\u001b[1;3mIndentationError('unindent does not match any outer indentation level', ('<string>', 6, 33, '            print(fibonacci(12))\\n', 6, -1))\u001b[0m\n",
      "Thought:\u001b[32;1m\u001b[1;3mThere was an indentation error in the code. Let me fix it and try again.\n",
      "Action: Python_REPL\n",
      "Action Input: def fibonacci(n):\n",
      "                if n <= 1:\n",
      "                    return n\n",
      "                else:\n",
      "                    return fibonacci(n-1) + fibonacci(n-2)\n",
      "print(fibonacci(12))\u001b[0m\n",
      "Observation: \u001b[36;1m\u001b[1;3m144\n",
      "\u001b[0m\n",
      "Thought:\u001b[32;1m\u001b[1;3mThe 12th number in the Fibonacci sequence is 144.\n",
      "Final Answer: 144\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'input': '第12个斐波那契数列的数字是多少？', 'output': '144'}"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "agent_executor.invoke({\"input\": \"第12个斐波那契数列的数字是多少？\"})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f502d83a",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
